package com.fernandomdo.ServiceAdministrator;

// Android Imports
import java.util.Calendar;
import java.util.Date;

import android.app.DialogFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.fernandomdo.ServiceAdministrator.Publisher.PublisherListItem;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface.DatabaseConstants;

public class CheckoutDialog extends DialogFragment implements OnClickListener, LoaderCallbacks<Cursor> {
	private static final String TAG = "CheckoutDialog";
	
	public final static String CHECKOUT = "checkout_dialog";
	public final static String TERRITORY_ID = "territory_id";
	private final static int TERRITORY_LOADER = 0;
	private final static int PUBLISHER_LOADER = 1;
	public static final String SIMPLE_DIALOG = "simple_dialog";
	public static final String ADVANCED_DIALOG = "advanced_dialog";
	private static boolean showAdvancedDialog = false;
	
	private Long territoryId;
	private Long publisherId;
	private String publisherName;
	private PublisherListItem publisher;
	private Button checkout;
	private Button cancel;
	private Context appContext;
	private Spinner territoryPicker;
	private Spinner publisherPicker;
	private SimpleCursorAdapter territoryAdapter;
	private SimpleCursorAdapter publisherAdapter;
	
	private static DatabaseInterface databaseInterface;
	
	
	/**
	 * Create a new instance of CheckOutDialog, providing the type of Dialog 
	 * and a territory id if necessary
	 * @param index
	 * @param territory_id
	 * @return
	 */
	public static CheckoutDialog newInstance(String type, Long territory_id) {
		CheckoutDialog checkoutDialog = new CheckoutDialog();
		Bundle args = new Bundle();
		
		if(type.equals(SIMPLE_DIALOG)) {
			showAdvancedDialog = false;
		}
		
		if(type.equals(ADVANCED_DIALOG)) {
			showAdvancedDialog = true;
		}
		
		args.putLong(CheckoutDialog.TERRITORY_ID, (territory_id != null) ? territory_id : Long.valueOf(0));
		checkoutDialog.setArguments(args);
		
		return checkoutDialog;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		appContext = getActivity().getApplicationContext();
		databaseInterface = new DatabaseInterface(appContext);
		
		Bundle bundle = getArguments();
		territoryId = bundle.getLong(CheckoutDialog.TERRITORY_ID);
		
		Log.d(TAG, "territoryId=" + territoryId);
		
		int style = DialogFragment.STYLE_NORMAL;
		int theme = 0;
		setStyle(style, theme);
	    
	    publisherAdapter = new SimpleCursorAdapter(appContext, android.R.layout.simple_spinner_item, null,
                new String[] { DatabaseConstants.PUBLISHER },
                new int[] { android.R.id.text1 }, 0);
	    publisherAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    
	    territoryAdapter = new SimpleCursorAdapter(appContext, android.R.layout.simple_spinner_item, null,
                new String[] { DatabaseConstants.TERRITORY },
                new int[] { android.R.id.text1 }, 0);
	    territoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    
	    if(showAdvancedDialog) {
	    	Log.d(TAG, "showing advanced Checkout Dialog");
	    	getLoaderManager().initLoader(TERRITORY_LOADER, null, this);
	    }
	    getLoaderManager().initLoader(PUBLISHER_LOADER, null, this);
	    
	}

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.dlg_checkout, container, false);
		
		territoryPicker = (Spinner)view.findViewById(R.id.spinner_territory);
		publisherPicker = (Spinner)view.findViewById(R.id.spinner_publisher);
		
		cancel 		= (Button)view.findViewById(R.id.btn_cancel);
		checkout 	= (Button)view.findViewById(R.id.btn_checkout);
		cancel.setOnClickListener(this);
		checkout.setOnClickListener(this);
		
		
		if(showAdvancedDialog) {
			territoryPicker.setAdapter(territoryAdapter);
			territoryPicker.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
					territoryId = id;
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					Log.d(TAG, "nothing was selected!");				
				}
				
			});
		}
		else {
			territoryPicker.setVisibility(View.GONE);
			view.findViewById(R.id.lbl_territory).setVisibility(View.GONE);
		}
		
		publisherPicker.setAdapter(publisherAdapter);
		publisherPicker.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				publisherId = id;
				TextView name = (TextView)view;
				publisherName = String.valueOf(name.getText());
				publisher = new PublisherListItem();
				publisher.id = publisherId;
				publisher.name = publisherName;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				Log.d(TAG, "nothing was selected!");				
			}
			
		});

		return view;
    }
	
	@Override
	public void onStop() {
		super.onStop();
		databaseInterface.readableDB.close();
	}
	

	
	@Override
	public void onClick(View v) {
	  	int duration = 5;
		CharSequence toastText;
		
		switch(v.getId()) {
			case R.id.btn_checkout:
				Date date = new Date();
				date = Calendar.getInstance().getTime();
				
				if((databaseInterface.checkOutTerritory(territoryId, publisher, date)) == true) {
					toastText = getString(R.string.check_out_message);;
				}
				else {
					toastText = getString(R.string.no_check_out_message);
				}
				
				Toast.makeText(appContext, toastText, duration).show();
				dismiss();
				
				// Only refresh the list if we opened the dialog from the List Fragment
				if(!showAdvancedDialog)
					ListTerritoryFragment.refreshList();
				
				break;
			case R.id.btn_cancel:
				this.dismiss();
				break;
	    	}
	    }
	    
	
	/**
	 * Simple Loader to retrieve the Territory list
	 */
	static public class TerritoryListLoader extends AsyncLoader<Cursor> {
		public TerritoryListLoader(Context context) {
			super(context);
		}
		
		@Override
		public Cursor loadInBackground() {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			Cursor cursor;
			final String[] FROM = { BaseColumns._ID, DatabaseConstants.TERRITORY };
			final String SELECTION = DatabaseConstants.STATUS + "=1";
			final String ORDER_BY = DatabaseConstants.TERRITORY;
			cursor =  databaseInterface.readableDB.query(DatabaseConstants.TERRITORY_TABLE,  FROM, SELECTION, null, null, null, ORDER_BY);
			return cursor;
		}
	}
	
	/**
	 * Simple Loader to retrieve the Publisher list
	 */
	static public class PublisherListLoader extends AsyncLoader<Cursor> {
		public PublisherListLoader(Context context) {
			super(context);
		}
		
		@Override
		public Cursor loadInBackground() {
			//Only open the database if it hasn't already been opened
			if(databaseInterface.readableDB == null || databaseInterface.readableDB.isOpen() == false) {
				databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			}
			
			Cursor cursor;
			final String[] FROM = { BaseColumns._ID, DatabaseConstants.PUBLISHER };
			final String ORDER_BY = DatabaseConstants.PUBLISHER;
			cursor =  databaseInterface.readableDB.query(DatabaseConstants.PUBLISHER_TABLE,  FROM, null, null, null, null, ORDER_BY);
			
			return cursor;
		}
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Loader<Cursor> loader = null;
		
		switch(id) {
		case TERRITORY_LOADER:
			loader = new TerritoryListLoader(appContext);
			break;
		case PUBLISHER_LOADER:
			loader = new PublisherListLoader(appContext);
			break;
		}
		
		return loader;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if(loader.getClass().equals(PublisherListLoader.class)) {
			Log.d(TAG, "Finished loading publisher info");
			publisherAdapter.swapCursor(cursor);
		}
		if(loader.getClass().equals(TerritoryListLoader.class)) {
			Log.d(TAG, "Finished loading territory info");
			territoryAdapter.swapCursor(cursor);
		}
	}
	
	
	/**
	 * Make sure that you override this method when you create an instance of DatabaseInterface
	 */
	
	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		if(loader.getClass().equals(PublisherListLoader.class)) {
			publisherAdapter.swapCursor(null);
		}
		if(loader.getClass().equals(TerritoryListLoader.class)) {
			territoryAdapter.swapCursor(null);
		}	
	}
}
